# 多线程如何返回值
import threading

import requests
from lxml import etree


class SearchMedicine2:
    def __init__(self, name):
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'cookie': '__finger=8c6cf3c4db94a8d5b1ea65208b7a06eb; Hm_lvt_f46dd4cc550b93aefde9b00265bb533d=1616479087; UM_distinctid=1785da96b84b0d-0b10b9c44101e6-5771031-1fa400-1785da96b85be5; CNZZDATA899409=cnzz_eid%3D1562633242-1616475837-https%253A%252F%252Fwww.sogou.com%252F%26ntime%3D1616475837; Hm_lvt_efd3be6e24f6aa90edbcdea9b260aac6=1616479088; CNZZDATA953100=cnzz_eid%3D1999569600-1616478788-https%253A%252F%252Fwww.sogou.com%252F%26ntime%3D1616478788; __asc=51716daf1785da96fd25a0658ef; __auc=51716daf1785da96fd25a0658ef; Hm_lpvt_f46dd4cc550b93aefde9b00265bb533d=1616479172; Hm_lpvt_efd3be6e24f6aa90edbcdea9b260aac6=1616479172'
        }
        self.base_url = url = 'https://ypk.familydoctor.com.cn/search/so/?KeyWord={}'
        self.name = name

    # 请求网页
    def connect_url(self, url):
        response = requests.get(url, headers=self.headers)
        text = response.content.decode('utf-8')
        html = etree.HTML(text)
        return html

    # 返回具体信息的网址
    def msgurl(self, url, num):
        html = self.connect_url(url)
        msg_url = html.xpath('//div[@class="search-result"]//dl[{}]/dd/h4/a/@href'.format(num))[0].strip()
        return ''.join([msg_url, 'instructions/'])

    # 传入网址，返回具体信息
    def messages(self, url):
        # url = https://ypk.familydoctor.com.cn/265257/instructions/
        html = self.connect_url(url)
        data_dict = {}
        # xpath
        try:
            # name = html.xpath('//table[@class="table-1"]//tr[1]/td/text()')[0].strip()  # 药品名
            name = html.xpath('//tr/th[contains(text(),"名称")]/../td/text()')[0].strip()  # 药品名
            data_dict['name'] = name
        except:
            data_dict['name'] = ''
        #################################################################################################
        try:
            # suit = html.xpath('//table[@class="table-1"]//tr[2]/td//text()')  # 适应症状
            suit = html.xpath('//tr/th[contains(text(),"适 ")]/../td//text()')  # 适应症状
            suits = []
            for b in suit:
                suits.append(b)
            data_dict['suit'] = suits
        except:
            data_dict['suit'] = ''
        #################################################################################################
        try:
            # usemethod = html.xpath('//table[@class="table-1"]//tr[3]/td/p')  # 使用方法
            # for i in usemethod:
            #     usemethod = " ".join(i.xpath('text()'))
            usemethod = html.xpath('//tr/th[contains(text(),"用量")]/../td//text()')  # 使用方法
            usemethods = []
            for b in usemethod:
                usemethods.append(b)

            data_dict['usemethod'] = usemethods
        except:
            data_dict['usemethod'] = ''
        #################################################################################################
        try:
            # lelment = html.xpath('//table[@class="table-1"]//tr[4]/td/text()')[0].strip()  # 成分
            lelment = html.xpath('//tr/th[contains(text(),"份")]/../td/text()')[0].strip()  # 成分
            data_dict['lelment'] = lelment
        except:
            data_dict['lelment'] = ''
        #################################################################################################
        try:
            # bad = html.xpath('//table[@class="table-1"]//tr[6]/td/p/text()')  # 不良反应
            bad = html.xpath('//tr/th[contains(text(),"不良")]/../td//text()')  # 不良反应
            bads = []
            for b in bad:
                bads.append(b)
            data_dict['bad'] = bads
        except:
            data_dict['bad'] = ''
        #################################################################################################
        try:
            # err = html.xpath('//table[@class="table-1"]//tr[7]/td//text()')  # 禁忌
            err = html.xpath('//tr/th[contains(text(),"禁")]/../td//text()')  # 禁忌
            errs = []
            for e in err:
                errs.append(e)
            data_dict['err'] = errs
        except:
            data_dict['err'] = ''
        #################################################################################################
        try:
            # heed = html.xpath('//table[@class="table-1"]//tr[8]/td/p/text()')  # 注意事项
            heed = html.xpath('//tr/th[contains(text(),"注意事")]/../td//text()')  # 注意事项
            # for i in heed:
            #     heed = " ".join(i.xpath('text()'))
            heeds = []
            for e in heed:
                heeds.append(e)
            data_dict['heed'] = heeds
        except:
            data_dict['heed'] = ''
        #################################################################################################
        try:
            # savemethod = html.xpath('//table[@class="table-1"]//tr[11]/td/text()')[0].strip()  # 保存方法
            savemethod = html.xpath('//tr/th[contains(text(),"贮")]/../td//text()')[0].strip()  # 保存方法
            data_dict['savemethod'] = savemethod
        except:
            data_dict['savemethod'] = ''
        #################################################################################################
        return data_dict

    # 传入网址，返回结果列表
    def list(self, url, num):
        # https://ypk.familydoctor.com.cn/search/so/?KeyWord=阿莫西林
        html = self.connect_url(url)
        data_dict = {}
        # imgs = '{}.img'.format(num)
        # names = '{}.name'.format(num)
        img = html.xpath('//div[@class="search-result"]//dl[{}]//img/@src'.format(num))[0].strip()
        name = html.xpath('//div[@class="search-result"]//dl[{}]//dd//h4//text()'.format(num))[0].strip()
        # data_dict['{}.img'.format(num)] = img
        # data_dict['{}.name'.format(num)] = name
        data_dict['img'] = img
        data_dict['name'] = name

        return data_dict

    def data(self):
        dict = {}
        for i in range(20):
            url = self.base_url.format(self.name)
            msg_url = self.msgurl(url, i + 1)
            msg_dict = self.messages(msg_url)
            show_dict = self.list(url, i + 1)

            # tem_dict = {}
            # tem_dict['show'] = show_dict
            # tem_dict['msg'] = msg_dict
            # dict[i + 1] = tem_dict

            msg_dict['img_url'] = show_dict['img']
            # dict[i + 1] = msg_dict
            dict[i] = msg_dict

        return dict


class SearchMedicine3:
    def __init__(self, name, num):
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'cookie': '__finger=8c6cf3c4db94a8d5b1ea65208b7a06eb; Hm_lvt_f46dd4cc550b93aefde9b00265bb533d=1616479087; UM_distinctid=1785da96b84b0d-0b10b9c44101e6-5771031-1fa400-1785da96b85be5; CNZZDATA899409=cnzz_eid%3D1562633242-1616475837-https%253A%252F%252Fwww.sogou.com%252F%26ntime%3D1616475837; Hm_lvt_efd3be6e24f6aa90edbcdea9b260aac6=1616479088; CNZZDATA953100=cnzz_eid%3D1999569600-1616478788-https%253A%252F%252Fwww.sogou.com%252F%26ntime%3D1616478788; __asc=51716daf1785da96fd25a0658ef; __auc=51716daf1785da96fd25a0658ef; Hm_lpvt_f46dd4cc550b93aefde9b00265bb533d=1616479172; Hm_lpvt_efd3be6e24f6aa90edbcdea9b260aac6=1616479172'
        }
        self.base_url = url = 'https://ypk.familydoctor.com.cn/search/so/?KeyWord={}'
        self.name = name
        self.num = num

    # 请求网页
    def connect_url(self, url):
        response = requests.get(url, headers=self.headers)
        text = response.content.decode('utf-8')
        html = etree.HTML(text)
        return html

    # 返回具体信息的网址
    def msgurl(self, url, num):
        html = self.connect_url(url)
        msg_url = html.xpath('//div[@class="search-result"]//dl[{}]/dd/h4/a/@href'.format(num))[0].strip()
        return ''.join([msg_url, 'instructions/'])

    # 传入网址，返回具体信息
    def messages(self, url):
        # url = https://ypk.familydoctor.com.cn/265257/instructions/
        html = self.connect_url(url)
        data_dict = {}
        # xpath
        try:
            # name = html.xpath('//table[@class="table-1"]//tr[1]/td/text()')[0].strip()  # 药品名
            name = html.xpath('//tr/th[contains(text(),"名称")]/../td/text()')[0].strip()  # 药品名
            data_dict['name'] = name
        except:
            data_dict['name'] = ''
        #################################################################################################
        try:
            # suit = html.xpath('//table[@class="table-1"]//tr[2]/td//text()')  # 适应症状
            suit = html.xpath('//tr/th[contains(text(),"适 ")]/../td//text()')  # 适应症状
            suits = []
            for b in suit:
                suits.append(b)
            data_dict['suit'] = suits
        except:
            data_dict['suit'] = ''
        #################################################################################################
        try:
            # usemethod = html.xpath('//table[@class="table-1"]//tr[3]/td/p')  # 使用方法
            # for i in usemethod:
            #     usemethod = " ".join(i.xpath('text()'))
            usemethod = html.xpath('//tr/th[contains(text(),"用量")]/../td//text()')  # 使用方法
            usemethods = []
            for b in usemethod:
                usemethods.append(b)

            data_dict['usemethod'] = usemethods
        except:
            data_dict['usemethod'] = ''
        #################################################################################################
        try:
            # lelment = html.xpath('//table[@class="table-1"]//tr[4]/td/text()')[0].strip()  # 成分
            lelment = html.xpath('//tr/th[contains(text(),"份")]/../td/text()')[0].strip()  # 成分
            data_dict['lelment'] = lelment
        except:
            data_dict['lelment'] = ''
        #################################################################################################
        try:
            # bad = html.xpath('//table[@class="table-1"]//tr[6]/td/p/text()')  # 不良反应
            bad = html.xpath('//tr/th[contains(text(),"不良")]/../td//text()')  # 不良反应
            bads = []
            for b in bad:
                bads.append(b)
            data_dict['bad'] = bads
        except:
            data_dict['bad'] = ''
        #################################################################################################
        try:
            # err = html.xpath('//table[@class="table-1"]//tr[7]/td//text()')  # 禁忌
            err = html.xpath('//tr/th[contains(text(),"禁")]/../td//text()')  # 禁忌
            errs = []
            for e in err:
                errs.append(e)
            data_dict['err'] = errs
        except:
            data_dict['err'] = ''
        #################################################################################################
        try:
            # heed = html.xpath('//table[@class="table-1"]//tr[8]/td/p/text()')  # 注意事项
            heed = html.xpath('//tr/th[contains(text(),"注意事")]/../td//text()')  # 注意事项
            # for i in heed:
            #     heed = " ".join(i.xpath('text()'))
            heeds = []
            for e in heed:
                heeds.append(e)
            data_dict['heed'] = heeds
        except:
            data_dict['heed'] = ''
        #################################################################################################
        try:
            # savemethod = html.xpath('//table[@class="table-1"]//tr[11]/td/text()')[0].strip()  # 保存方法
            savemethod = html.xpath('//tr/th[contains(text(),"贮")]/../td//text()')[0].strip()  # 保存方法
            data_dict['savemethod'] = savemethod
        except:
            data_dict['savemethod'] = ''
        #################################################################################################
        return data_dict

    # 传入网址，返回结果列表
    def list(self, url, num):
        # https://ypk.familydoctor.com.cn/search/so/?KeyWord=阿莫西林
        html = self.connect_url(url)
        data_dict = {}
        img = html.xpath('//div[@class="search-result"]//dl[{}]//img/@src'.format(num))[0].strip()
        name = html.xpath('//div[@class="search-result"]//dl[{}]//dd//h4//text()'.format(num))[0].strip()
        data_dict['img'] = img
        data_dict['name'] = name

        return data_dict

    def data(self):
        dict = {}
        url = self.base_url.format(self.name)
        i = int(self.num) - 1
        msg_url = self.msgurl(url, i + 1)
        msg_dict = self.messages(msg_url)
        show_dict = self.list(url, i + 1)

        msg_dict['img_url'] = show_dict['img']

        # 为了格式统一，这个废弃
        # tem_dict = {}
        # tem_dict['show'] = show_dict
        # tem_dict['msg'] = msg_dict
        # dict[i + 1] = tem_dict
        dict[i + 1] = msg_dict
        # return dict
        return dict


class recommendMedicine:
    def __init__(self):
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'cookie': '__finger=8c6cf3c4db94a8d5b1ea65208b7a06eb; Hm_lvt_f46dd4cc550b93aefde9b00265bb533d=1616479087; UM_distinctid=1785da96b84b0d-0b10b9c44101e6-5771031-1fa400-1785da96b85be5; CNZZDATA899409=cnzz_eid%3D1562633242-1616475837-https%253A%252F%252Fwww.sogou.com%252F%26ntime%3D1616475837; Hm_lvt_efd3be6e24f6aa90edbcdea9b260aac6=1616479088; CNZZDATA953100=cnzz_eid%3D1999569600-1616478788-https%253A%252F%252Fwww.sogou.com%252F%26ntime%3D1616478788; __asc=51716daf1785da96fd25a0658ef; __auc=51716daf1785da96fd25a0658ef; Hm_lpvt_f46dd4cc550b93aefde9b00265bb533d=1616479172; Hm_lpvt_efd3be6e24f6aa90edbcdea9b260aac6=1616479172'
        }
        self.base_url = 'https://ypk.familydoctor.com.cn/'

    # 请求网页
    def connect_url(self, url):
        response = requests.get(url, headers=self.headers)
        text = response.content.decode('utf-8')
        html = etree.HTML(text)
        return html
    # //div[@id="tabContent1_0"]/ul/li//a           名字
    #  //div[@id="tabContent1_0"]/ul//a/img/@src    图片链接


class MyThread(threading.Thread):

    def __init__(self, func, args=()):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        try:
            return self.result  # 如果子线程不使用join方法，此处可能会报没有self.result的错误
        except Exception:
            return None


def search2(name):
    search = SearchMedicine2(name)
    data = search.data()
    return data
